package com.hmyd.hmyd_android;

import java.util.Stack;

import org.apache.http.client.CookieStore;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.Application;
import android.app.Notification;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.text.TextUtils;
import android.widget.Toast;

import com.hmyd.hmyd_android.dto.App;
import com.hmyd.hmyd_android.dto.AppMall;
import com.hmyd.hmyd_android.dto.Version;
import com.hmyd.hmyd_android.utils.CustomNotificationHandler;
import com.hmyd.hmyd_android.utils.HMYDExceptionHandler;
import com.hmyd.hmyd_android.utils.Utils;
import com.hmyd.hmyd_android.view.LockPatternUtils;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.HttpUtils;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.umeng.message.PushAgent;
import com.umeng.message.UTrack;
import com.umeng.message.UmengMessageHandler;
import com.umeng.message.entity.UMessage;
import com.umeng.socialize.utils.Log;

/**
 * <pre>
 * 此类的作用主要是实现应用程序集的全局变量， 
 * 也就是任何一个Activity中都可以访问的变量，
 * 它不会因为Activity的生命周期结束而消失。
 * </pre>
 * 
 * @author sun_t
 */
public class AppBasic extends Application {
	// 获取上下文
	private static Context context;
	
	public static boolean isShow = false;
	public static boolean isLogin = false;
	public static boolean isCheckIned = false;	//是否签到
	public static double totalScore = 0;// 总积分
	public static String realName;
	public static String avatar;
	public static String username;
	public static String nickname;
	public static String urlToken;
	public static String certNo;
	public static String securityLevel;
	public static boolean isSetSecurityCode;
	public static boolean isCanUpdateNickname;
	public static long unReadMessageCount;
	public static String tel;
	public static String email;
	public static boolean isVerifiedEmail;
	public static boolean isSetSecurityQuestion;
	public static boolean isBind;
	public static String bindQQ;
	public static double  rewardScore;
	public static double  nextTimeScore;
	public static boolean haveNewHotActivity;
	public static boolean haveNewArticel;
	public static boolean isSetSinaPayPassword;	//是否设置支付密码
	public static String birthday;	//生日信息
	public static String memberRating;	//会员等级
	public static String memberRank;	//会员头衔
	/**
	 * 设备唯一标识,这个标识取自当前手机的硬件信息、手机rom版本号、制造商拼接而成
	 * 有极小的可能性会造成有重复现象的发生
	 */
	public static String mDeviceId;

	private static AppBasic instance_;

	private static Stack<Activity> activityStack;

	private static BitmapUtils bitmapUtils;

	// 获取服务器时间
	public static long ServerTime = 0;

	// 请求链接超时时间
	private static int DEFAULT_CONN_TIMEOUT = 30 * 1000;
	// 默认CookieStore信息存储
	public static CookieStore cookieStore;

	public static String key;// 获取密匙（key）

	public static App app;
	
	public static AppMall appMall;

	private static LockPatternUtils mLockPatternUtils;
	private PushAgent mPushAgent;

	public  static Version version = null;

	/**
	 * 单例模式
	 * 
	 * @return
	 */
	public static AppBasic getInstance() {
		if (null == instance_) {
			instance_ = new AppBasic();
		}
		return instance_;
	}

	public void init(){  
		//设置该CrashHandler为程序的默认处理器    
		/*
		 * 开发过程中，请务必将以下两行注释掉
		 */
//		HMYDExceptionHandler catchExcep = new HMYDExceptionHandler();  
//		Thread.setDefaultUncaughtExceptionHandler(catchExcep);   
	} 


	public static void initDeviceId(Context context) {
		if(context == null) {
			Log.e("设备id获取失败");
			return;
		}
		mDeviceId = "35" + Build.BOARD.length()%10 + Build.BRAND.length()%10 + 
				Build.CPU_ABI.length()%10 + Build.DEVICE.length()%10 + Build.DISPLAY.length()%10 + 
				Build.HOST.length()%10 + Build.ID.length()%10 + Build.MANUFACTURER.length()%10 + 
				Build.MODEL.length()%10 + Build.PRODUCT.length()%10 + Build.TAGS.length()%10 + 
				Build.TYPE.length()%10 + Build.USER.length()%10;
		System.out.println("mDeviceId:"+mDeviceId);
		if(TextUtils.isEmpty(mDeviceId) || Utils.isAllZero(mDeviceId)) {
			Toast.makeText(context, "设备id无效", Toast.LENGTH_SHORT).show();
		}
	}


	/**
	 * 获取BitmapUtils单例模式
	 * 
	 * @param appContext
	 * @return
	 */
	public static BitmapUtils getBitmapUtils(Context appContext) {
		if (bitmapUtils == null) {
			bitmapUtils = new BitmapUtils(appContext);
		}
		return bitmapUtils;
	}

	/**
	 * 获取HttpUtils单例模式
	 * 
	 * @param appContext
	 * @return
	 */
	public static HttpUtils getHttpUtils() {
		return new HttpUtils(DEFAULT_CONN_TIMEOUT);
	}

	/**
	 * 获取手势解锁
	 * 
	 * @return
	 */
	public  LockPatternUtils getLockPatternUtils() {
		return mLockPatternUtils;
	}

	/**
	 * 添加activity到堆栈中
	 * 
	 * @param activity
	 */
	public void addActivity(Activity activity){
		if (null == activityStack) {
			activityStack = new Stack<Activity>();
		}
		activityStack.add(activity);
	}

	/**
	 * 获取当前Activity
	 * 
	 * @return
	 */
	public Activity currentActivity() {
		if (null != activityStack && !activityStack.isEmpty()) {
			return activityStack.lastElement();
		}
		return null;
	}

	/**
	 * 结束当前Activity
	 */
	public void finishCurrentActivity(){
		finishActivity(activityStack.lastElement());
	}

	/**
	 * 结束指定activity
	 * @param activity
	 */
	public void finishActivity(Activity activity){
		if (null != activityStack) {
			activityStack.remove(activity);
			activity.finish();
			activity = null;
		}
	}

	/**
	 * 结束所有的Activity
	 */
	public void finishAllActivity() {
		for (Activity activity_ : activityStack) {
			if (null != activity_) {
				activity_.finish();
			}
		}
		activityStack.clear();
	}

	/**
	 * 判断指定activity知否在栈中
	 * @param context
	 * @return
	 */
	public boolean isActivityLive(Class clazz) {
		for (Activity activity2 : activityStack) {
			String name = activity2.toString();
			if(name.substring(0, name.indexOf("@")).equals(clazz.getName())) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 退出应用程序
	 */
	public void exitSystem() {
		try {
			// 结束所有Activity
			finishAllActivity();
			// 杀死后台进程
			ActivityManager amg = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
			amg.killBackgroundProcesses(context.getPackageName());

			/*// 停止程序开启的服务，保证程序退出后不会常驻内存
			Intent intent = new Intent();
			intent.setAction(context.getPackageName());
			stopService(intent);*/

			// 退出程序
			System.exit(0);
		} catch (Exception e) {
			System.exit(0);
		}
	}

	@Override
	public void onCreate() {
		super.onCreate();
		//获取Context  
        context = getApplicationContext();  
		
		initImageLoader(context);// 初始化全局图片加载配置
		mLockPatternUtils = new LockPatternUtils(this);

		initMessage();// 初始化友盟推送
	}
	
	// 获取当前上下文  
    public static Context getContextObject(){  
        return context;  
    }  

	private void initMessage() {

		mPushAgent = PushAgent.getInstance(this);
		mPushAgent.setDebugMode(true);
		UmengMessageHandler messageHandler = new UmengMessageHandler() {
			@Override
			public void dealWithCustomMessage(final Context context, final UMessage msg) {
				new Handler().post(new Runnable() {

					@Override
					public void run() {
						// 对自定义消息的处理方式，点击或者忽略
						boolean isClickOrDismissed = true;
						if (isClickOrDismissed) {
							// 自定义消息的点击统计
							UTrack.getInstance(context).trackMsgClick(msg);
						} else {
							// 自定义消息的忽略统计
							UTrack.getInstance(context).trackMsgDismissed(msg);
						}
						Toast.makeText(context, msg.custom, Toast.LENGTH_LONG).show();
					}
				});
			}

			/**
			 * 参考集成文档的1.6.4 http://dev.umeng.com/push/android/integration#1_6_4
			 * */
			@Override
			public Notification getNotification(Context context, UMessage msg) {
				switch (msg.builder_id) {
				case 1:
					return null;
				default:
					// 默认为0，若填写的builder_id并不存在，也使用默认。
					return super.getNotification(context, msg);
				}
			}
		};
		mPushAgent.setMessageHandler(messageHandler);

		/**
		 * 该Handler是在BroadcastReceiver中被调用，故
		 * 如果需启动Activity，需添加Intent.FLAG_ACTIVITY_NEW_TASK 参考集成文档的1.6.2
		 * http://dev.umeng.com/push/android/integration#1_6_2
		 * */
		/*
		 * UmengNotificationClickHandler notificationClickHandler = new
		 * UmengNotificationClickHandler(){
		 * 
		 * @Override public void dealWithCustomAction(Context context, UMessage
		 * msg) { Toast.makeText(context, msg.custom, Toast.LENGTH_LONG).show();
		 * } };
		 */
		CustomNotificationHandler notificationClickHandler = new CustomNotificationHandler();
		mPushAgent.setNotificationClickHandler(notificationClickHandler);

	}

	private void initImageLoader(Context context) {

		ImageLoaderConfiguration.Builder config = new ImageLoaderConfiguration.Builder(context);
		config.threadPriority(Thread.NORM_PRIORITY - 2);
		config.denyCacheImageMultipleSizesInMemory();
		config.diskCacheFileNameGenerator(new Md5FileNameGenerator());
		config.diskCacheSize(50 * 1024 * 1024); // 50 MiB
		config.tasksProcessingOrder(QueueProcessingType.LIFO);

		ImageLoader.getInstance().init(config.build());

	}

	@Override
	public void onLowMemory() {
		super.onLowMemory();
	}

	@Override
	public void onTerminate() {
		super.onTerminate();
	}
}
